package com.itx.gatewayx.controller;

import com.itx.gatewayx.common.constants.SystemConstants;
import com.itx.gatewayx.common.model.ResponseResult;
import com.itx.gatewayx.domain.dto.LoginDTO;
import com.itx.gatewayx.domain.vo.LoginVO;
import com.itx.gatewayx.service.IAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * 认证控制器
 *
 * @author itx
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private IAuthService authService;

    /**
     * 登录方法
     *
     * @param loginDTO 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Mono<ResponseResult<LoginVO>> login(@RequestBody LoginDTO loginDTO) {
        return authService.login(loginDTO)
                .map(ResponseResult::success)
                .onErrorResume(e -> Mono.just(ResponseResult.error(e.getMessage())));
    }

    /**
     * 登出方法
     *
     * @param token 令牌
     * @return 结果
     */
    @PostMapping("/logout")
    public Mono<ResponseResult<Boolean>> logout(@RequestHeader(value = SystemConstants.AUTHORIZATION_HEADER, required = false) String token) {
        if (token != null && token.startsWith(SystemConstants.TOKEN_PREFIX)) {
            token = token.substring(SystemConstants.TOKEN_PREFIX.length());
        }
        
        final String finalToken = token;
        return authService.logout(finalToken)
                .<ResponseResult<Boolean>>map(result -> result ? ResponseResult.success(true) : ResponseResult.error("登出失败"))
                .defaultIfEmpty(ResponseResult.error("登出失败"))
                .onErrorReturn(ResponseResult.error("登出失败"));
    }

    /**
     * 刷新令牌
     *
     * @param refreshToken 刷新令牌
     * @return 结果
     */
    @PostMapping("/refresh")
    public Mono<ResponseResult<LoginVO>> refreshToken(@RequestHeader(value = SystemConstants.REFRESH_TOKEN_HEADER) String refreshToken) {
        return authService.refreshToken(refreshToken)
                .map(ResponseResult::success)
                .onErrorResume(e -> Mono.just(ResponseResult.error(e.getMessage())));
    }

    /**
     * 获取验证码
     *
     * @return 验证码信息
     */
    @GetMapping("/captcha")
    public Mono<ResponseResult<String>> captcha() {
        return authService.generateCaptcha()
                .<ResponseResult<String>>map(ResponseResult::success)
                .defaultIfEmpty(ResponseResult.error("获取验证码失败"))
                .onErrorReturn(ResponseResult.error("获取验证码失败"));
    }
} 